import { AService, ServiceType } from "../Base/AService";
import { ErrorCode } from "../Base/ErrorCode";
import { IPEndPoint } from "../Base/IPEndPoint";
import { WChannel } from "./WChannel";

export class WService extends AService {
    private readonly idChannels = new Map<string, WChannel>();
    private websokcet: WebSocket;
    constructor(serviceType: ServiceType)
    constructor(serviceType: ServiceType, ipEndPoint: IPEndPoint)
    constructor(serviceType: ServiceType, ipEndPoint?: IPEndPoint) {
        super();
        this.ServiceType = serviceType;
        if (ipEndPoint) {
            this.websokcet = new WebSocket(`ws://${ipEndPoint.toString()}`);
            this.websokcet.onopen = (e) => {
                console.log("");
            };
            this.websokcet.onmessage = (e) => {
                e.data;
            }
            //this.websokcet.send();
        }
    }
    private Create(ipEndPoint: IPEndPoint, id: Long) {
        let channel = new WChannel(id, ipEndPoint, this);
        this.idChannels.set(channel.Id.toString(), channel);
        return channel;
    }
    private Get1(id: Long) {
        let channel = this.idChannels.get(id.toString());
        return channel;
    }
    public Update(): void {
        // for (const kv of this.idChannels) {
        //     kv[1].u
        // }
    }
    public Remove(id: Long): void {
        let channel = this.idChannels.get(id.toString());
        if (channel) {
            channel.Dispose();
            this.idChannels.delete(id.toString());
        }
    }
    public IsDispose(): boolean {
        return this.websokcet == null;
    }
    protected Get(id: Long, address: IPEndPoint): void {
        if (this.idChannels.has(id.toString())) {
            return;
        }
        this.Create(address, id);
    }
    public Dispose(): void {
        this.websokcet?.close();
        for (const kv of this.idChannels) {
            kv[1].Dispose();
        }
        this.idChannels.clear();
    }
    protected Send(channelId: Long, actorId: Long, stream: DataView): void {
        try {
            let aChannel = this.Get1(channelId);
            if (aChannel == null) {
                this.OnError(channelId, ErrorCode.ERR_SendMessageNotFoundTChannel);
                return;
            }
            aChannel.Send(actorId, stream);
        }
        catch (e) {
            console.error(e);
        }
    }
}